//
//  OpenGLTexture3D.m
//  NeHe Lesson 06
//
//  Created by Jeff LaMarche on 12/24/08.
//  Copyright 2008 Jeff LaMarche Consulting. All rights reserved.
//

#import "OpenGLTexture3D.h"


@implementation OpenGLTexture3D
@synthesize filename;
// Height and width are required for pvrt compressed textures. They will be ignored for images that can be used to create UIImage
- (id)initWithFilename:(NSString *)inFilename width:(GLuint)inWidth height:(GLuint)inHeight;
{
	if ((self = [super init]))
	{
		self.filename = inFilename;

		glGenTextures(1, texture);
		glBindTexture(GL_TEXTURE_2D, texture[0]);

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); 
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); 
		glBlendFunc(GL_ONE, GL_SRC_COLOR);

		NSData *texData = [[NSData alloc] initWithContentsOfFile:inFilename];

		// Assumes pvr4 is RGB not RGBA, which is how texturetool generates them
		if ([inFilename hasSuffix:@".pvr4"])
        {
			glCompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, inWidth, inHeight, 0, (inWidth * inHeight) / 2, [texData bytes]);
            [texData release];
        }
		else if ([inFilename hasSuffix:@".pvr2"])
        {
			glCompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG, inWidth, inHeight, 0, (inWidth * inHeight) / 2, [texData bytes]);
            [texData release];
        }
		else
		{
            if(texData == nil)
            {
                return nil;
            }
			UIImage *image = [[UIImage alloc] initWithData:texData];
            [texData release]; 
            if (image == nil)
            {
				return nil;
			}
			CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
			void *imageData = malloc( inHeight * inWidth * 4 );
			CGContextRef context = CGBitmapContextCreate( imageData, inWidth, inHeight, 8, 4 * inWidth, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big );
			CGColorSpaceRelease( colorSpace );
			CGContextClearRect( context, CGRectMake( 0, 0, inWidth, inHeight ) );
			CGContextDrawImage( context, CGRectMake( 0, 0, inWidth, inHeight ), image.CGImage );
            
			glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, inWidth, inHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);
            
			CGContextRelease(context);
			
			free(imageData);
			[image release];
            
        }
    }
	return self;
}

- (void)bind
{
	//NSLog(@"Binding texture: %@ (OGL: %d", filename, texture[0]);
	glBindTexture(GL_TEXTURE_2D, texture[0]);
}
- (void)dealloc
{
	glDeleteTextures(1, &texture[0]);
	[filename release];
	[super dealloc];
}
@end
